package com.gs.cd.utils.api;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.gs.cd.api.ApiResult;
import com.gs.cd.api.ApiResultType;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

/**
 * create by hippo  2020/6/7
 *
 * @Description
 **/

@Log4j2
public class ApiResultParserUtils {


    public static <T> T parseObject(ApiResult apiResult, Class<T> targetClass) {
        checkResultCode(apiResult);
        try {
            return JSONUtil.toBean(JSONUtil.toJsonStr(apiResult.getData()), targetClass);
        } catch (Exception e) {
            log.error(String.format("==========\t\n解析错误apiResult：%s\n==========", apiResult));
            throw new RuntimeException("parse apiResult 2 " + targetClass.getName() + " error\n");
        }

    }

    public static <T> T parseObject(String apiResultJson, Class<T> targetClass) {
        ApiResult apiResult = null;
        try {
            apiResult = JSONUtil.toBean(apiResultJson, ApiResult.class);
        } catch (Exception e) {
            throw new RuntimeException(String.format("非有效apiResult对象：%s", apiResultJson));
        }
        return parseObject(apiResult, targetClass);
    }

    public static <T> List<T> parseList(ApiResult apiResult, Class<T> targetClass) {
        checkResultCode(apiResult);
        try {
            return JSONUtil.parseArray(JSONUtil.toJsonStr(apiResult.getData())).toList(targetClass);
        } catch (Exception e) {
            log.error(String.format("==========\t\n解析错误apiResult：%s\n==========", apiResult));
            throw new RuntimeException("parse apiResult to list 4 " + targetClass.getName() + " error\n");
        }
    }

    public static <T> List<T> parseList(String apiResultJson, Class<T> targetClass) {
        ApiResult apiResult = null;
        try {
            apiResult = JSONUtil.toBean(apiResultJson, ApiResult.class);
        } catch (Exception e) {
            throw new RuntimeException(String.format("非有效apiResult对象：%s", apiResultJson));
        }
        return parseList(apiResult, targetClass);
    }

    /**
     * todo 需自定义异常
     *
     * @param apiResult
     */
    private static void checkResultCode(ApiResult apiResult) {
        if (apiResult == null) throw new RuntimeException("apiResult 为 null");
        if (apiResult.getCode() != ApiResultType.SUCCESS.getValue()) {
            throw new RuntimeException(apiResult.getMsg());
        }
    }


}